package com.zretc.auth.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.shaded.com.google.gson.JsonObject;
import com.zhenzi.sms.JsonUtil;
import com.zhenzi.sms.ZhenziSmsClient;
import com.zretc.api.pojo.SysUser;
import com.zretc.auth.dao.SysUserMapper;
import com.zretc.auth.dao.SysUserRoleMapper;
import com.zretc.auth.dao.UserInfoMapper;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import com.zretc.redis.service.RedisService;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

@Service
@Transactional
public class RegistryService {
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private RedisService redisService;
    public RespResult registry(SysUser user)
    {
        user.setRoleName("学生");
        if(userMapper.isPhoneExisted(user.getPhone())!=0)return R.fail(410,"手机号已经存在");
        userMapper.addSingleRecord(user);
        sysUserRoleMapper.addSingleRecord(user.getId(),1);
        userInfoMapper.addSingleRecord(user);
        return R.genRespObj(200,"注册成功",null);
    }
    public RespResult sendVerifyCodeMessage(String phone) throws Exception {
        String apiUrl="https://sms_developer.zhenzikj.com";
        String appId="113950";
        String appSecret="914f6715-ad0e-4991-8b1a-350edd011bff";
        String code= String.valueOf(1000 + (int)(Math.random() * (9999 - 1000)));
        ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("number", phone);
        params.put("templateId", "12991");
        String[] templateParams = new String[2];
        redisService.setCacheObject("VerifyCode:"+phone,code);
        templateParams[0] = code;
        templateParams[1] = "5分钟";
        params.put("templateParams", templateParams);
        String result = client.send(params);
        RespResult r = JSON.parseObject(result,RespResult.class);
        return r;
    }
    public boolean checkVerifyCode(String verifyCode,String phone)
    {
        if(verifyCode==null)return false;
        String code=redisService.getCacheObject("VerifyCode:"+phone);
        if(code==null)return false;
        return verifyCode.equals(code);
    }
}
